﻿using Ionic.Zip;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace SetChannel
{
    public partial class FormMain : Form
    {
        private OpenFileDialog openFileDialog;
        private FolderBrowserDialog folderBrowser;
        private string apkPath = "";
        private string apkName = "";
        private const string channelPre = "channel_";
        private const string channelSplit = "#";

        private List<Channel> channelList;
        public FormMain()
        {
            InitializeComponent();

            init();

        }

        private void init()
        {
            channelList = new List<Channel>();
            readChannelFile();

            foreach (Channel item in channelList)
            {
                listViewChannel.Items.Add(new ListViewItem(new string[] { item.lineNumber + "", item.name, item.state }));
            }
        }

        /// <summary>
        /// 从文件中读取渠道列表
        /// </summary>
        public void readChannelFile()
        {
            string path = "@Channel_List.txt";

            if (!File.Exists(path))
            {
                MessageBox.Show("渠道列表文件不存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }

            StreamReader sr = new StreamReader(path, Encoding.Default);
            string lineName;
            int lineNumber = 1;
            while ((lineName = sr.ReadLine()) != null)
            {
                if (!string.IsNullOrEmpty(lineName))
                {
                    Channel chanel = new Channel();
                    chanel.lineNumber = lineNumber;
                    chanel.name = lineName;
                    chanel.state = "";

                    channelList.Add(chanel);
                    ++lineNumber;
                }
            }
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            if (openFileDialog == null)
            {
                openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "APK文件|*.apk";
                openFileDialog.RestoreDirectory = true;
                openFileDialog.Multiselect = false;
                openFileDialog.FilterIndex = 1;
            }

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                apkName = openFileDialog.SafeFileName;
                apkPath = openFileDialog.FileName;
                tbAPKPath.Text = apkPath;

            }
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(apkPath))
            {
                MessageBox.Show("APK文件Path为空,请先选择APK文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (!File.Exists(apkPath))
            {
                MessageBox.Show("APK文件不存在,请检查APK文件路径", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (string.IsNullOrEmpty(tbApKPreName.Text))
            {
                MessageBox.Show("APK文件前缀名不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (string.IsNullOrEmpty(tbApkVersion.Text))
            {
                MessageBox.Show("APK版本不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            btnCreate.Enabled = false;
            btnCreate.Text = "生成中···";
            foreach (ListViewItem viewItem in listViewChannel.Items)
            {
                createAPK(viewItem.SubItems[1].Text);
                viewItem.SubItems[2].Text = "完成";
            }

            btnCreate.Enabled = true;
            btnCreate.Text = "生成";
        }

        private void createAPK(string channelName)
        {
            string channelFileName = channelPre + channelName;
            try
            {
                //创建渠道文件
                if (!File.Exists(channelFileName))
                {
                    using (File.Create(channelFileName)) { }
                }
                addFileInAPK(apkPath, channelFileName, channelName);

                File.Delete(channelFileName);//删除渠道文件
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        private void addFileInAPK(string apkFile, string channelFile, string channelName)
        {
            if (!File.Exists(apkFile))
            {
                MessageBox.Show("复制操作失败,请重试···", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (!File.Exists(channelFile))
            {
                MessageBox.Show("渠道文件创建失败,请重试···", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(tbApKPreName.Text);
                if (channelName.Contains(channelSplit))
                {
                    string[] channels = channelName.Split(channelSplit[0]);
                    foreach (string item in channels)
                    {
                        sb.Append("_" + item);
                    }
                }
                else {
                    sb.Append("_" + channelName);
                }

                sb.Append("_" + tbApkVersion.Text);

                if (checkBoxDate.Checked)
                {
                    //DateTime dt = DateTime.Now;
                    //sb.Append("_" + dt.ToString("yyyyMMdd"));

                    sb.Append("_" + dateTimePicker.Value.Date.ToString("yyyyMMdd"));
                }

                sb.Append(".apk");

                string copyFileFullName = apkPath.Replace(apkName, sb.ToString());

                using (ZipFile zip = ZipFile.Read(apkPath))
                {
                    zip.AddFile(channelFile, "META-INF/");
                    zip.Save(copyFileFullName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void checkBoxDate_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxDate.Checked)
            {
                dateTimePicker.Enabled = true;
            }
            else {
                dateTimePicker.Enabled = false;
            }
        }


        private void btnSelectApk_Click(object sender, EventArgs e)
        {
            folderBrowser = new FolderBrowserDialog();
            folderBrowser.Description = "请APK文件夹";
            if (folderBrowser.ShowDialog() == DialogResult.OK)
            {
                string foldPath = folderBrowser.SelectedPath;
                tbApkDir.Text = foldPath;

                Directory.GetFiles(foldPath);
            }
        }

        private void genMutiApks_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbChannelMore.Text))
            {
                MessageBox.Show("多文件打包渠道不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (string.IsNullOrEmpty(tbApkDir.Text))
            {
                MessageBox.Show("多文件打包路径不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            DirectoryInfo dirInfo = Directory.CreateDirectory(tbApkDir.Text + "/ChannelApk");
            if (!dirInfo.Exists)
            {
                MessageBox.Show("APK存放文件夹创建失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            string channelName = tbChannelMore.Text;
            string channelFileName = channelPre + channelName;
            try
            {
                //创建渠道文件
                if (!File.Exists(channelFileName))
                {
                    using (File.Create(channelFileName)) { }
                }

                string[] apkPath = Directory.GetFiles(tbApkDir.Text);
                foreach (string apkPathItem in apkPath)
                {
                    addMoreFileInAPK(apkPathItem, channelFileName, channelName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }


        private void addMoreFileInAPK(string apkFile, string channelFile, string channelName)
        {
            if (!File.Exists(apkFile))
            {
                MessageBox.Show("复制操作失败,请重试···", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (!File.Exists(channelFile))
            {
                MessageBox.Show("渠道文件创建失败,请重试···", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(Path.GetFileName(apkFile).Replace(".apk", ""));
                if (channelName.Contains(channelSplit))
                {
                    string[] channels = channelName.Split(channelSplit[0]);
                    foreach (string item in channels)
                    {
                        sb.Append("_" + item);
                    }
                }
                else {
                    sb.Append("_" + channelName);
                }

                sb.Append(".apk");

                string apkFullApth = tbApkDir.Text + "/ChannelApk/" + sb.ToString();

                using (ZipFile zip = ZipFile.Read(apkFile))
                {
                    zip.AddFile(channelFile, "META-INF/");
                    zip.Save(apkFullApth);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

    }

}
